Web Technologies

BLOG for Web Technologies

Freewares, Free E-Books Download, SEO, Tips, Tricks, Tweaks, Latest News, .Net, PHP, ASP, ASP.Net, CSP, MS SQL Server, MySQL, Database
earnptr.com
Monday, April 18, 2011
Send Email Using Gmail in ASP.Net

To send email using gmail in asp.net, write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)
{
   MailMessage mail = new MailMessage();
   mail.To.Add("jainamit.agra@gmail.com");
   mail.To.Add("amit_jain_online@yahoo.com");
   mail.From = new MailAddress("jainamit.agra@gmail.com");
   mail.Subject = "Email using Gmail";
    string Body = "Hi, this mail is to test sending mail"+
                  "using Gmail in ASP.NET";   mail.Body = Body;
    mail.IsBodyHtml = true;
   SmtpClient smtp = new SmtpClient();
   smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
   smtp.Credentials = new System.Net.NetworkCredential
        ("YourUserName@gmail.com","YourGmailPassword");
 //Or your Smtp Email ID and Password
   smtp.EnableSsl = true;   smtp.Send(mail); }

VB.NET code

Imports System.Net.Mail
   Protected  Sub Button1_Click (ByVal sender As Object, ByVal e As EventArgs)
   Dim mail As MailMessage =  New MailMessage()
    mail.To.Add("jainamit.agra@gmail.com")
   mail.To.Add("amit_jain_online@yahoo.com")
   mail.From = New MailAddress("jainamit.agra@gmail.com")
   mail.Subject = "Email using Gmail"
     String Body = "Hi, this mail is to test sending mail"+
                  "using Gmail in ASP.NET"   mail.Body = Body
     mail.IsBodyHtml = True
   Dim smtp As SmtpClient =  New SmtpClient()
    smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
   smtp.Credentials = New System.Net.NetworkCredential
        ("YourUserName@gmail.com","YourGmailPassword")
   smtp.EnableSsl = True
   smtp.Send(mail)
 End Sub  

You also need to enable POP by going to settings > Forwarding and POP in your gmail account

Change YourUserName@gmail.com to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file
<system.net>
 <defaultProxy>
 <proxy proxyaddress="YourProxyIpAddress"/>
 defaultProxy> 
>

If you are still having problems them try changing port number to 587
smtp.Host = "smtp.gmail.com,587";

If you still having problems then try changing code as mentioned below
SmtpClient smtp = new SmtpClient(); 
smtp.Host = "smtp.gmail.com"; 
smtp.Port = 587; 
smtp.UseDefaultCredentials = False; 
smtp.Credentials = new System.Net.NetworkCredential 
  ("YourUserName@gmail.com","YourGmailPassword"); 
smtp.EnableSsl = true; smtp.Send(mail);

This will definitely helps you.

Labels: , ,

posted by WebTeks @ 7:59 PM   39 comments
Sunday, January 3, 2010
Speed Optimization in ASP.NET 2.0 Web Applications

Page and Server Controls

The following topics give you an idea about how to use pages and controls efficiently in your web application:

Use HTML controls whenever possible

HTML controls is lighter than server controls especially if you are using server controls with its default properties. Server controls generally is easier to use than HTML controls, and on the other side they are slower than HTML controls. So, it is recommended to use HTML controls whenever possible and avoid using unnecessary server controls.

Avoid round trips to server whenever possible

Using server controls will extensively increase round trips to the server via their post back events which wastes a lot of time. You typically need to avoid these unnecessary round trips or post back events as possible. For example, validating user inputs can always (or at least in most cases) take place in the client side. There is no need to send these inputs to the server to check their validity. In general you should avoid code that causes a round trip to the server.

The Page.IsPostBack Property

The Page.IspostBack Boolean property indicates whether this page is loaded as a response to a round trip to the server, or it is being loaded for the first time. This property helps you to write the code needed for the first time the page is loaded, and avoiding running this same code each time the page is posted back. You can use this property efficiently in the page_load event. This event is executed each time a page is loaded, so you can use this property conditionally to avoid unnecessary re-running of certain code.

Server Control's AutoPostBack Property

Always set this property to false except when you really need to turn it on. This property automatically post back to the server after some action takes place depending on the type of the control. For example, in the Text Control this property automatically post back to the server after the text is modified which is a great deal of processing cost and hence much slower performance and most importantly a poor user experience.

Leave Buffering on

It is important to leave page buffering in its on state to improve your page speed, unless you have a serious reason to turn it off.

Server Controls View State

Server control by default saves all the values of its properties between round trips, and this increases both page size and processing time which is of course an undesired behavior. Disable the server control view state whenever possible. For example, if you bind data to a server control each time the page is posted back, then it is useful to disable the control's view state property. This reduces page size and processing time.

Methods for redirection

There are many ways you can use to redirect a user from the current page to another one in the same application, however the most efficient methods to do this are: the Server.Transfer method or cross-page posting.

Web Applications

The following topics give you some tips about how to make an efficient web application:

Precompilation

When an already deployed ASP.NET web application page is requested for the first time, that page needs to be compiled (by the server) before the user gets a response. The compiled page or code is then cached so that we need not to compile it again for the coming requests. It is clear that the first user gets a slow response than the following users. This scenario is repeated for each web page and code file within your web site.

When using precompilation then the ASP.NET entire web application pages and code files will be compiled ahead. So, when a user requests a page from this web application he will get it in a reasonable response time whatever he is the first user or not.

Precompiling the entire web application before making it available to users provides faster response times. This is very useful on frequently updated large web applications.

Encoding

By default ASP.NET applications use UTF-8 encoding. If your application is using ASCII codes only, it is preferred to set your encoding to ASCII to improve your application performance.

Authentication

It is recommended to turn authentication off when you do not need it. The authentication mode for ASP.NET applications is windows mode. In many cases it is preferred to turn off the authentication in the 'machin.config' file located on your server and to enable it only for applications that really need it.

Debug Mode

Before deploying your web application you have to disable the debug mode. This makes your deployed application faster than before. You can disable or enable debug mode form within your application's 'web.config' file under the 'system.web' section as a property to the 'compilation' item. You can set it to 'true' or 'false'.

Coding Practices

The following topics give you guidelines to write efficient code:

Page Size

Web page with a large size consumes more bandwidth over the network during its transfer. Page size is affected by the numbers and types of controls it contains, and the number of images and data used to render the page. The larger the slower, this is the rule. Try to make your web pages small and as light as possible. This will improve response time.

Exception Handling

It is better for your application in terms of performance to detect in your code conditions that may cause exceptions instead of relying on catching exceptions and handling them. You should avoid common exceptions like null reference, dividing by zero , and so on by checking them manually in your code.

The following code gives you two examples: The first one uses exception handling and the second tests for a condition. Both examples produce the same result, but the performance of the first one suffers significantly.

    8         ' This is not recommended.
9 Try
10 Output = 100 / number
11 Catch ex As Exception
12 Output = 0
13 End Try
14
15 ' This is preferred.
16 If Not (number = 0) Then
17 Output = 100 / number
18
Else
19 Output = 0
20 End If

Garbage Collector

ASP.NET provides automatic garbage collection and memory management. The garbage collector's main task is to allocate and release memory for your application. There are some tips you can take care of when you writing your application's code to make the garbage collector works for your benefit:

Avoid using objects with a Finalize sub as possible and avoid freeing resources in Finalize functions.
Avoid allocating too much memory per web page because the garbage collector will have to do more work for each request and this increases CPU utilization (not to mention you can go out of memories in larger web applications)
Avoid having unnecessary pointers to objects because this makes these objects alive until you free them yourself within your code not in an automatic way.

Use Try / Finally

If you are to use exceptions anyway, then always use a try / finally block to handle your exceptions. In the finally section you can close your resources if an exception occurred or not. If an exception occurs, then the finally section will clean up your resources and frees them up.

String Concatenation

Many string concatenations are time consuming operations. So, if you want to concatenate many strings such as to dynamically build some HTML or XML strings then use theSystem.Text.StringBuilder object instead of system.string data type. The append method of the StringBuilder class is more efficient than concatenation.

Threading

If your application contains some operation that consumes time and resources, then instead of blocking the application flow awaiting for this process or operation to be finished it is recommended to create a separate thread for this blocking operation. By threading you will save your application normal flow from delays. Examples of time consuming operations that can be moved to another thread other than the main program thread are: querying on a database and waiting for results, and extensive IO operations.

For further information

Refer to the online copy of Microsoft Developers Network at http://msdn.microsoft.com or use your own local copy of MSDN.

Labels: ,

posted by WebTeks @ 9:58 PM   1 comments
Saturday, October 24, 2009
SQL SERVER – UDF – Function to Convert Text String to Title Case – Proper Case

Following function will convert any string to Title Case. I have this function for long time. I do not remember that if I wrote it myself or I modified from original source.

Run Following T-SQL statement in query analyzer:

SELECT dbo.TitleCase('This function will convert this string to title case!')

The output will be displayed in Results pan as follows:

This Function Will Convert This String To Title Case!

T-SQL code of the function is:

CREATE FUNCTION TitleCase (@InputString VARCHAR(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE
@Index INT
DECLARE
@Char CHAR(1)
DECLARE @OutputString VARCHAR(255)
SET @OutputString = LOWER(@InputString)
SET @Index = 2
SET @OutputString =
STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))
WHILE @Index <= LEN(@InputString)
BEGIN
SET
@Char = SUBSTRING(@InputString, @Index, 1)
IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/','&','''','(')
IF @Index + 1 <= LEN(@InputString)
BEGIN
IF
@Char != ''''
OR
UPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'
SET @OutputString =
STUFF(@OutputString, @Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index+ 1, 1)))
END
SET
@Index = @Index + 1
END
RETURN
ISNULL(@OutputString,'')
END

Labels: , , ,

posted by WebTeks @ 8:11 PM   1 comments
Thursday, September 10, 2009
Error Logging using ASP.NET 2.0
Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application.

In this article, we will adopt a simple mechanism to log errors and exceptions in our website. We will be using a mechanism where the user will be redirected to a separate page whenever an error is encountered in the application. Simultaneously, the error will get logged in a text file on the server. The error file will be created on a daily basis, whenever the error is encountered. Having said that, let us now see some code.

Step 1: Start by creating an Error folder where all errors will be logged. Right click the website > New Folder. Rename the folder to “Error”. Also add a web.config file, if one does not already exist in your site. Right click the website > Add New Item > Web.config.

Step 2: Now we will create the error handler code. To do so, right click your website > Add New Item > select Class. Rename the class to ‘ErrHandler.cs’ and click on ‘Add’. When you do so, you will be prompted with a message to place the class in ‘App_Code’ folder. Accept the message to place the class in the 'App_Code' folder.

Step 3: Now let us add functionality to the ErrHandler class. This class will accept the error message and write the message in a text file. One text file will be created for each day. If the text file already exists, the message will be appended to the text file. If not, a new text file will be created based on today’s date and error message will be written in it.

The code will look similar to the following:

C#

/// Handles error by accepting the error message

    /// Displays the page on which the error occured

    public static void WriteError(string errorMessage)

    {

        try

        {

            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";

            if(!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))

            {

               File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();

            }

            using (StreamWriter w =File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))

            {

                w.WriteLine("\r\nLog Entry : ");

                w.WriteLine("{0}",DateTime.Now.ToString(CultureInfo.InvariantCulture));

                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +

                              ". Error Message:" + errorMessage;

                w.WriteLine(err);

                w.WriteLine("__________________________");

                w.Flush();

                w.Close();

            }

        }

        catch (Exception ex)

        {

            WriteError(ex.Message);

        }

 

    }

VB.NET

''' Handles error by accepting the error message

    ''' Displays the page on which the error occured

    Public Shared Sub WriteError(ByVal errorMessage As String)

        Try

            Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"

            If (NotFile.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then

                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()

            End If

            Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))

                w.WriteLine(Constants.vbCrLf & "Log Entry : ")

                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))

                Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage

                w.WriteLine(err)

                w.WriteLine("__________________________")

                w.Flush()

                w.Close()

            End Using

        Catch ex As Exception

            WriteError(ex.Message)

        End Try

 

    End Sub

That was our ErrHandler class. We will now see how to use this Error Handler class and handle errors at the page level as well as at the application level.

Handling errors at Page Level

In the Default.aspx, drag and drop a button from the toolbox. Rename this button to btnError and set the Text as ‘Throw Handled Exception’. Here we will throw an exception. Since we have a catch block defined, the exception will be caught and the error will be logged in the Error folder. Since a text file with today’s date, does not exists, a new text file will be created by the code.

The button click handler will look similar to the following:

C#

protected void btnHandled_Click(object sender, EventArgs e)

    {

        try

        {

            throw new Exception("Sample Exception");

        }

        catch (Exception ex)

        {

            // Log the error to a text file in the Error folder

            ErrHandler.WriteError(ex.Message);

        }

    }

VB.NET

Protected Sub btnHandled_Click(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles btnHandled.Click

        Try

            Throw New Exception()

        Catch ex As Exception

            ' Log the error to a text file in the Error folder

            ErrHandler.WriteError(ex.Message)

        End Try

    End Sub

Now with the code in place, run the application and click on the button. Since we have handled the error and logged the exception in our code, you will not notice anything when the button is clicked. However, close the application and refresh the Error folder. You will see a new text file created with today’s date. The exception has been logged successfully as shown below. The date and time will differ on your machine.

Log Entry :

01/11/2008 23:33:46

Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception

__________________________

Redirecting users on unhandled errors

Let us see how to catch unhandled errors and redirect the user to a different page, whenever such an unhandled error occurs at the application level.

To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:

C#

 void Application_Error(object sender, EventArgs e)

    {

        // Code that runs when an unhandled error occurs

        Exception objErr = Server.GetLastError().GetBaseException();

        string err = "Error in: " + Request.Url.ToString() +

                          ". Error Message:" + objErr.Message.ToString();

        // Log the error

        ErrHandler.WriteError(err);       

    }

VB.NET

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

        ' Code that runs when an unhandled error occurs       

        Dim objErr As Exception = Server.GetLastError().GetBaseException()

        Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()

        ' Log the error

        ErrHandler.WriteError(err)

    End Sub

We capture the error using the Server.GetLastError(). Now to redirect users to a different page whenever an unhandled error occurs, open your web.config file and locate the <customErrors> tag and uncomment it. After removing the comment, the tag will look similar to the following code:

<!--

            The <customErrors> section enables configuration

            of what to do if/when an unhandled error occurs

            during the execution of a request. Specifically,

            it enables developers to configure html error pages

            to be displayed in place of a error stack trace.        -->

 

                  <customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">

                        <errorstatusCode="403"redirect="NoAccess.htm" />

                        <errorstatusCode="404"redirect="FileNotFound.htm"/>

                  </customErrors>

Now change:

 mode="RemoteOnly"tomode="On"

defaultRedirect="GenericErrorPage.htm" todefaultRedirect="ErrorPage.aspx"

The modified code will now look like this:

<customErrorsmode="On"defaultRedirect="ErrorPage.aspx">

                        <errorstatusCode="403"redirect="NoAccess.htm" />

                        <errorstatusCode="404"redirect="FileNotFound.htm"/>

                  </customErrors>

This configuration will now redirect the user to an Error page when an error occurs. Let us create this error page and display some message to the user.

Right Click Project > Add New Item> Create a new ErrorPage.aspx page in the application and display a sample message on the page informing the user that an error has occurred.

To test our functionality, go back to Default.aspx, add another button and rename it to btnUnhandled and set its Text property to ‘Throw Unhandled Exception’. Here instead of throwing the exception as we did for ‘btn_Error’, we will introduce a ‘Divide By Zero’ exception and not handle it. Observe that there is no try catch block as shown below. So when the error occurs, the user will be redirected to the ‘ErrorPage.aspx’ as a result of the changes made in our web.config file.

C#

protected void btnHandled_Click(object sender, EventArgs e)

    {

        try

        {

            throw new Exception("Sample Exception");

        }

        catch (Exception ex)

        {

            // Log the error to a text file in the Error folder

            ErrHandler.WriteError(ex.Message);

        }

    }

VB.NET

Protected Sub btnUnhandled_Click(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles btnUnhandled.Click

        Dim i As Integer = 1

        Dim j As Integer = 0

        Response.Write(i \ j)

    End Sub

 

Run the application and click on the ‘Throw Unhandled Exception’ button. You will observe that the user will be automatically redirected to the Error Page and the error will be logged in the Error folder. Well that’s it.

In this article, we saw how to implement a simple error logging system in our application. Logging errors can be very useful and helps us detect errors during development and operation of a website. ASP.NET also provides some advanced options titled under ‘Health Monitoring’ where the errors can be stored in Sql Server or even emailed to the administrator based on the criticality of it.

Labels: , ,

posted by WebTeks @ 3:19 AM   3 comments
Previous Post
Archives
Links
Template by

Free Blogger Templates

BLOGGER

Subscribe in NewsGator Online Subscribe in Rojo Add to Google Add to netvibes Subscribe in Bloglines Web Developement Blogs - BlogCatalog Blog Directory Blogarama - The Blog Directory Blog Directory & Search engine Computers Blogs - Blog Top Sites Top Computers blogs